package com.huanglejing.shanggou.presenterimpl

import android.support.v4.util.LruCache
import com.cfzx.http.NetClient
import com.google.gson.JsonObject
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.common.BaseModel
import com.huanglejing.shanggou.utils.C
import rx.Observable

/**
 * @param operation 对应的网络操作key
 *@param isUserLogin 是否需要用户登录
 */
class BaseCacheRequestImpl private constructor(val operation: String, val strategy: UrlStrategy? = null) : BaseModel.BaseCacheModel<Map<String, Any>, JsonObject> {

    enum class UrlStrategy {
        OLD,
        NEW;
    }

    private var key: String = ""

    //需要缓存吗？只缓存第一页
    override fun requestFor(t: Map<String, Any>): Observable<JsonObject> {
        return Observable.just(t)?.flatMap {
            if (strategy==UrlStrategy.NEW){
                NetClient.daDiService.postEncode(operation, t, emptyMap())
            }else{
                NetClient.oldDaDiService.post(operation, t, emptyMap())
            }

        } ?: Observable.just(JsonObject())
    }

    override fun requestForGet(t: Map<String, Any>): Observable<JsonObject> {
        return Observable.just(t)?.flatMap {
            if (strategy==UrlStrategy.NEW){
                NetClient.daDiService.get(operation, t, emptyMap())
            }else{
                NetClient.oldDaDiService.get(operation, t, emptyMap())
            }

        } ?: Observable.just(JsonObject())
    }

    override fun requestWithHeaders(t: Map<String, Any>, headers: Map<String, String>): Observable<JsonObject> {
        return Observable.just(null)
    }

    override fun requestFor(): Observable<JsonObject> {
        return requestFor(emptyMap())
    }

    override fun requestForGet(): Observable<JsonObject> {
        return requestForGet(emptyMap())
    }

    /**
     * 会保存缓存
     * key : $url_$param_$cityCode_$userId
     */
    override fun requestForCache(t: Map<String, Any>): Observable<JsonObject> {
        return Observable.just(null)

    }

    override fun requestForGetCache(t: Map<String, Any>): Observable<JsonObject> {
        return Observable.just(null)
    }

    override fun abortLruCache() {

    }

    companion object {
        private val pooledInstance = LruCache<String, BaseCacheRequestImpl>(128)  //最多存储128个对象

        fun getInstance(api: String, strategy: UrlStrategy? = null): BaseCacheRequestImpl {
            val ins = pooledInstance.get(api) ?: (BaseCacheRequestImpl(api,strategy)).apply {
                pooledInstance.put(api, this)
            }
            KLog.d("request : $api ; pooled(${pooledInstance.size()})  $pooledInstance: ${pooledInstance.snapshot()}")
            return ins
        }
    }

    private val hexString by lazy { Integer.toHexString(this.hashCode()) }
    override fun toString(): String {
        return "Impl($operation)@$hexString"
    }
}
